package com.YxyBackMange.Shiro;

import com.YxyBackMange.Entity.Sys.SysPower;
import com.YxyBackMange.Entity.Sys.SysRole;
import com.YxyBackMange.Entity.Sys.SysUser;
import com.YxyBackMange.Mapper.Sys.SysRoleMapper;
import com.YxyBackMange.Mapper.Sys.SysUserMapper;
import com.YxyBackMange.Util.MD5;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * Created by Administrator on 2017/1/11.
 */
@Service
@Transactional
public class MyShiro extends AuthorizingRealm {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    /**
     * 权限认证
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        // 从 principals获取主身份信息
        // 将getPrimaryPrincipal方法返回值转为真实身份类型（在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型），
        SysUser sysUser= (SysUser) principals.getPrimaryPrincipal();
        List<SysRole> list=sysRoleMapper.selectSysRoleByUserId(sysUser.getId());
        Set<String> shiroRoles=new HashSet<String>() ;//shiro所需要的角色
        Set<String> powers=new HashSet<String>();
        for (SysRole sysRole: list) {
            shiroRoles.add(sysRole.getRoleMark());
            for (SysPower sysPower:sysRole.getSysPowerSet())
            {
                powers.add(sysPower.getPowerUrl());
            }
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addRoles(shiroRoles);
        info.addStringPermissions(powers);
        return info;
    }

    /**
     * 登录认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进行登录认证操作");
        UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
        String password = String.valueOf(token.getPassword());
        System.err.println("接受到的密码"+password);
        SysUser user=new SysUser();

        user.setIdentity(token.getUsername());
        //查出是否有此用户
        user = sysUserMapper.selectOne(user);
        if(user!=null){
            password = MD5.createMD5(password);
            password = MD5.createMD5(password + user.getSalt());
            token.setPassword(password.toCharArray());
            return new SimpleAuthenticationInfo(user,user.getToken(), getName());
        }
        return null;
    }
}
